package com.infra.micro.id.domain.repository;

import com.infra.micro.id.domain.entity.IdSegmentExample;
import com.infra.micro.id.domain.entity.IdSegmentPO;
import com.infra.micro.id.domain.mapper.IdSegmentMapper;
import com.infra.micro.id.domain.mapper.ext.IdSegmentExtMapper;
import com.infra.micro.id.model.req.QueryIdSegmentByCondReq;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Repository
public class IdSegmentRepository {
    @Resource
    private IdSegmentMapper idSegmentMapper;
    @Resource
    private IdSegmentExtMapper idSegmentExtMapper;

    public IdSegmentPO queryById(Long segmentId) {
        return idSegmentMapper.selectByPrimaryKey(segmentId);
    }

    public int insert(int appId) {
        IdSegmentPO record = new IdSegmentPO();
        record.setAppId(appId);
        return idSegmentMapper.insertSelective(record);
    }

    public List<IdSegmentPO> queryByCond(QueryIdSegmentByCondReq req) {
        IdSegmentExample example = new IdSegmentExample();
        IdSegmentExample.Criteria criteria = example.createCriteria();
        if (req.getAppId() != null) {
            criteria.andAppIdEqualTo(req.getAppId());
        }
        return idSegmentMapper.selectByExample(example);
    }

    public IdSegmentPO queryByAppId(Integer appId) {
        IdSegmentExample example = new IdSegmentExample();
        example.createCriteria().andAppIdEqualTo(appId);
        return idSegmentMapper.selectByExample(example).stream().findFirst().orElse(null);
    }

    public int update(IdSegmentPO record) {
        return idSegmentMapper.updateByPrimaryKeySelective(record);
    }

    public int insert(IdSegmentPO record) {
        return idSegmentMapper.insertSelective(record);
    }

    /**
     * 更新最大id且返回更新后的号段
     *
     * @param appId 业务应用
     * @return 更新后的号段
     */
    @Transactional(rollbackFor = Exception.class)
    public IdSegmentPO updateMaxIdAndGet(Integer appId) {
        idSegmentExtMapper.updateMaxIdByAppId(appId);
        return this.queryByAppId(appId);
    }

    /**
     * 更新最大id且返回更新后的号段
     *
     * @param appId    业务应用
     * @param nextStep 下一个步长
     * @return 更新后的号段
     */
    @Transactional(rollbackFor = Exception.class)
    public IdSegmentPO updateMaxIdByStepAndGet(Integer appId, int nextStep) {
        idSegmentExtMapper.updateMaxIdByStepAndGet(appId, nextStep);
        return this.queryByAppId(appId);
    }

}
